<script setup>
import { ref, onMounted } from 'vue'
import { Table, Button, Modal, Input, message } from 'ant-design-vue'
import { getArchiveList, deleteArchive } from '@/api/archive'
import { getOrganizationOptions, getPositionOptions } from '@/api/system'

const columns = [
  { title: '员工编号', dataIndex: 'code', key: 'code', width: 120 },
  { title: '姓名', dataIndex: 'name', key: 'name', width: 100 },
  { title: '所属机构', dataIndex: 'organization', key: 'organization', width: 150 },
  { title: '职位', dataIndex: 'position', key: 'position', width: 120 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '操作', key: 'action', width: 150 },
]

const dataSource = ref([])
const loading = ref(false)
const deleteVisible = ref(false)
const deleteRecord = ref(null)
const confirmText = ref('')

// 搜索表单
const searchForm = ref({
  keyword: '',
  department: undefined,
  position: undefined,
})

// 机构选项
const organizationOptions = ref([])
// 职位选项
const positionOptions = ref([])

// 分页相关
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total) => `共 ${total} 条`,
})

// 获取机构选项
const fetchOrganizationOptions = async () => {
  try {
    const response = await getOrganizationOptions()
    if (response && response.list) {
      organizationOptions.value = response.list.map((item) => ({
        value: item.value,
        label: item.label,
      }))
    } else {
      organizationOptions.value = []
    }
  } catch (error) {
    console.error('获取机构选项失败:', error)
    organizationOptions.value = []
  }
}

// 获取职位选项
const fetchPositionOptions = async () => {
  try {
    const response = await getPositionOptions()
    if (response && response.list) {
      positionOptions.value = response.list.map((item) => ({
        value: item.value,
        label: item.label,
      }))
    } else {
      positionOptions.value = []
    }
  } catch (error) {
    console.error('获取职位选项失败:', error)
    positionOptions.value = []
  }
}

// 获取档案列表
const fetchArchiveList = async (page = 1, pageSize = 10) => {
  loading.value = true
  try {
    const params = {
      keyword: searchForm.value.keyword || undefined,
      department: searchForm.value.department || undefined,
      position: searchForm.value.position || undefined,
      page,
      pageSize,
    }

    // 移除 undefined 的字段
    Object.keys(params).forEach((key) => {
      if (params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await getArchiveList(params)

    if (response && response.list) {
      dataSource.value = response.list.map((item) => ({
        ...item,
        key: item.id,
        // 兼容字段名：如果返回的是 org，映射为 organization
        organization: item.organization || item.org,
      }))
      // 更新分页信息
      pagination.value.total = response.total || 0
      pagination.value.current = response.page || page
      pagination.value.pageSize = response.pageSize || pageSize
    } else {
      dataSource.value = []
      pagination.value.total = 0
    }
  } catch (error) {
    console.error('获取档案列表失败:', error)
    message.error('获取数据失败')
    dataSource.value = []
    pagination.value.total = 0
  } finally {
    loading.value = false
  }
}

// 处理分页变化
const handleTableChange = (pag) => {
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
  fetchArchiveList(pag.current, pag.pageSize)
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  fetchArchiveList(1, pagination.value.pageSize)
}

// 重置
const handleReset = () => {
  searchForm.value = {
    keyword: '',
    department: undefined,
    position: undefined,
  }
  pagination.value.current = 1
  fetchArchiveList(1, pagination.value.pageSize)
}

const handleDelete = (record) => {
  deleteRecord.value = record
  deleteVisible.value = true
  confirmText.value = ''
}

const handleDeleteConfirm = async () => {
  if (confirmText.value !== 'DELETE') {
    message.warning('请输入 DELETE 确认删除')
    return
  }

  try {
    const response = await deleteArchive(deleteRecord.value.id, confirmText.value)

    if (response && response.status) {
      message.success('删除成功（逻辑删除）')
      deleteVisible.value = false
      confirmText.value = ''

      // 更新状态
      const index = dataSource.value.findIndex((item) => item.key === deleteRecord.value.key)
      if (index !== -1) {
        dataSource.value[index].status = response.status || '已删除'
      }

      // 刷新列表
      fetchArchiveList(pagination.value.current, pagination.value.pageSize)
    } else {
      message.error('删除失败，请稍后重试')
    }
  } catch (error) {
    console.error('删除档案失败:', error)
    message.error('删除失败，请稍后重试')
  }
}

onMounted(() => {
  fetchOrganizationOptions()
  fetchPositionOptions()
  fetchArchiveList(1, pagination.value.pageSize)
})
</script>

<template>
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">人力资源档案删除</h1>
      <p class="page-desc">
        对档案数据进行删除处理，删除前会检查关联数据，重要数据删除需要复核专员审批
      </p>
    </div>

    <div class="page-content">
      <div class="warning-box">
        <div class="warning-icon">⚠️</div>
        <div class="warning-content">
          <div class="warning-title">删除操作说明</div>
          <div class="warning-text">
            • 删除操作以逻辑删除为主，物理删除需特殊权限<br />
            • 删除前系统会自动检查关联数据（薪酬记录、考勤记录等）<br />
            • 重要数据删除需要复核专员审批<br />
            • 所有删除操作都会完整记录日志
          </div>
        </div>
      </div>

      <div class="search-card">
        <div class="search-form">
          <a-row :gutter="16">
            <a-col :span="6">
              <a-input
                v-model:value="searchForm.keyword"
                placeholder="员工编号/姓名"
                allow-clear
              />
            </a-col>
            <a-col :span="6">
              <a-select
                v-model:value="searchForm.department"
                placeholder="所属机构"
                allow-clear
                style="width: 100%"
              >
                <a-select-option
                  v-for="option in organizationOptions"
                  :key="option.value"
                  :value="option.value"
                >
                  {{ option.label }}
                </a-select-option>
              </a-select>
            </a-col>
            <a-col :span="6">
              <a-select
                v-model:value="searchForm.position"
                placeholder="职位"
                allow-clear
                style="width: 100%"
              >
                <a-select-option
                  v-for="option in positionOptions"
                  :key="option.value"
                  :value="option.value"
                >
                  {{ option.label }}
                </a-select-option>
              </a-select>
            </a-col>
          </a-row>
          <div class="search-actions">
            <a-space>
              <a-button type="primary" @click="handleSearch">查询</a-button>
              <a-button @click="handleReset">重置</a-button>
            </a-space>
          </div>
        </div>
      </div>

      <div class="table-wrapper">
        <a-table
          :columns="columns"
          :data-source="dataSource"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'status'">
              <a-tag
                :color="
                  record.status === '已生效' || record.status === '在职'
                    ? 'green'
                    : record.status === '已恢复'
                      ? 'gold'
                      : record.status === '已删除'
                        ? 'red'
                        : 'default'
                "
              >
                {{ record.status }}
              </a-tag>
            </template>
            <template v-if="column.key === 'action'">
              <a-button
                v-if="record.status !== '已删除'"
                type="link"
                size="small"
                danger
                @click="handleDelete(record)"
              >
                删除
              </a-button>
              <span v-else style="color: #86868b; font-size: 12px">已删除</span>
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <a-modal v-model:open="deleteVisible" title="确认删除" width="500px" @ok="handleDeleteConfirm">
      <div class="delete-info">
        <p><strong>员工编号：</strong>{{ deleteRecord?.code }}</p>
        <p><strong>姓名：</strong>{{ deleteRecord?.name }}</p>
        <p><strong>所属机构：</strong>{{ deleteRecord?.organization || deleteRecord?.org }}</p>
        <p><strong>职位：</strong>{{ deleteRecord?.position }}</p>
      </div>
      <div class="delete-warning">
        <p style="color: #ff3b30; font-weight: 500; margin-bottom: 12px">
          此操作将删除该员工档案，删除前系统会检查关联数据。
        </p>
        <p style="margin-bottom: 8px">
          请输入 <strong style="color: #ff3b30">DELETE</strong> 确认删除：
        </p>
        <a-input v-model:value="confirmText" placeholder="请输入 DELETE" style="margin-top: 8px" />
      </div>
    </a-modal>
  </div>
</template>

<style scoped>
.page-container {
  background: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(20px) saturate(180%);
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.04);
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.06);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0 0 8px 0;
  letter-spacing: -0.5px;
}

.page-desc {
  font-size: 14px;
  color: #86868b;
  margin: 0;
}

.page-content {
  margin-top: 24px;
}

.warning-box {
  display: flex;
  gap: 16px;
  background: #fff3cd;
  border: 1px solid #ffc107;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 24px;
}

.warning-icon {
  font-size: 24px;
  flex-shrink: 0;
}

.warning-content {
  flex: 1;
}

.warning-title {
  font-size: 14px;
  font-weight: 600;
  color: #856404;
  margin-bottom: 8px;
}

.warning-text {
  font-size: 13px;
  color: #856404;
  line-height: 1.6;
}

.search-card {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.02);
}

.search-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.search-actions {
  display: flex;
  justify-content: flex-end;
}

.table-wrapper {
  background: #fff;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.02);
}

.status-badge {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.active {
  background: rgba(52, 199, 89, 0.1);
  color: #34c759;
}

.status-badge.deleted {
  background: rgba(255, 59, 48, 0.1);
  color: #ff3b30;
}

.delete-info {
  background: #f5f5f7;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.delete-info p {
  margin: 8px 0;
  font-size: 14px;
  color: #1d1d1f;
}

.delete-warning {
  margin-top: 16px;
}

.delete-warning p {
  font-size: 14px;
  color: #1d1d1f;
  line-height: 1.6;
}
</style>
